﻿unit CriticalSection;

interface

uses
  Winapi.Windows;

type
  TCriticalSection = class
  protected
    BeginTime: Cardinal;
    LockName: String;
    FCriticalSection: TRTLCriticalSection;
  public
    constructor Create;
    destructor Destroy; override;
    procedure SetLockName(ALockName: String);
    procedure Lock;
    procedure UnLock;
  end;

implementation

constructor TCriticalSection.Create;
begin
  inherited Create;
  InitializeCriticalSection(FCriticalSection);
end;

destructor TCriticalSection.Destroy;
begin
  DeleteCriticalSection(FCriticalSection);
  inherited Destroy;
end;

procedure TCriticalSection.SetLockName(ALockName: String);
begin
  LockName := ALockName;
end;

procedure TCriticalSection.Lock;
begin
  {$IFDEF _IOCP_LOCK_MONITOR}
    InterlockedIncrement(_IOCPMonitor.m_LockGlobalCount);
    BeginTime := GetTickCount;
    if Assigned(_GlobalLogger) then
      _GlobalLogger.AppendErrorLogMessage('锁: %s, 进入时等待个数: %d.',[LockName, _IOCPMonitor.m_LockGlobalCount]);
  {$ENDIF}
  EnterCriticalSection(FCriticalSection);
  {$IFDEF _IOCP_LOCK_MONITOR}
    if ( Assigned(_GlobalLogger) and (GetTickCount - BeginTime>0)) then
      _GlobalLogger.AppendErrorLogMessage('锁: %s, 等待个数: %d, Lock前等待时间: %d.',
        [LockName, _IOCPMonitor.m_LockGlobalCount, GetTickCount - BeginTime]);
  {$ENDIF}
end;

procedure TCriticalSection.UnLock;
begin
  LeaveCriticalSection(FCriticalSection);
  {$IFDEF _IOCP_LOCK_MONITOR}
  InterlockedDecrement(_IOCPMonitor.m_LockGlobalCount);
  if (Assigned(_GlobalLogger) and (GetTickCount- BeginTime > 0)) then
    _GlobalLogger.AppendErrorLogMessage('锁: %s, 处理时间: %d.',
      [m_LockName, GetTickCount - BeginTime] );
  if Assigned(_GlobalLogger) then
    _GlobalLogger.AppendErrorLogMessage('锁: %s退出, 等待个数: %d.',[LockName, _IOCPMonitor.m_LockGlobalCount]);
  {$ENDIF}
end;


end.







